﻿#if UNITY_WECHAT_GAME
using WeChatWASM;

namespace LitFramework
{
    public class GameState_ForceUpdate_WxMiniGame : IState
    {
        public StateMechine Master { get; set; }

        private WXUpdateManager updateManager;

        public void OnEnter(params object[] values)
        {
            GameManager.Instance.InitState = "ForceUpdate Check...";
            GameManager.Instance.InitProgress = 0;

            updateManager = WX.GetUpdateManager();
            updateManager.OnCheckForUpdate(OnCheckForUpdate);
        }

        public void OnUpdate()
        {

        }

        public void OnExit()
        {

        }

        private void OnCheckForUpdate(OnCheckForUpdateListenerResult result)
        {
            if (result.hasUpdate)
            {
                updateManager.OnUpdateReady(OnUpdateReady);
                updateManager.OnUpdateFailed(OnUpdateFailed);
            }
            else
            {
                Master.TurnToState<GameState_HotUpdate>();
            }
        }

        private void OnUpdateReady(GeneralCallbackResult result)
        {
            ShowModalOption option = new ShowModalOption();
            option.title = "";
            option.content = "";
            option.success = result =>
            {
                if (result.confirm)
                    updateManager.ApplyUpdate();
            };
            WX.ShowModal(option);
        }

        private void OnUpdateFailed(GeneralCallbackResult result)
        {
            TipPanel.ShowTip("新版本下载失败", "重试", () =>
            {
                RestartMiniProgramOption option = new RestartMiniProgramOption();
                WX.RestartMiniProgram(option);
            });
        }
    }
}
#endif